package com.tj.jinzao.activity;

import android.app.Activity;
import android.view.KeyEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.tj.jinzao.R;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.base.IBaseView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.HealthReport;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.presenter.HealthReportPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.ChooseConfigDialog;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


/**
 * 检测中activity
 * Created by wjy on 2019/1/5.
 */
public class FaceDetectingActivity extends BaseActivity implements IBaseView<List<HealthReport>> {

    @BindView(R.id.iv_circle)
    ImageView mCircleView;
    @BindView(R.id.pb_detecting)
    ProgressBar mProgressBar;

    private int mProgress;

    private HealthReportPresenter mPresenter;
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;

    private ChooseConfigDialog mDialog;
    private void dialog(String content){
        mDialog = new ChooseConfigDialog(FaceDetectingActivity.this, content);
        mDialog.show();
        mDialog.setOnClickLinstener(new ChooseConfigDialog.OnClickLinstener() {
            @Override
            public void onConfig(String mContent) {
                mDialog.dismiss();
                if(mContent.equals("1")){
                    finish();
                }

            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(mDialog!=null&&mDialog.isShowing()){
                return true;
            }
            dialog("退出，检测流程全部终止");
        }
        return true;

    }

    public void detachView() {
        onUnsubscribe();
    }

    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_face_detecting;
    }
    private void getJc(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("uid", UserManager.getInstance().getUser().getId());
        addSubscription(mApiService.getJC(hashMap), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String list) {
                if(list.equals("true")){
                    mPresenter = new HealthReportPresenter(FaceDetectingActivity.this);
                    mPresenter.examination();
                    Animation rotate = AnimationUtils.loadAnimation(FaceDetectingActivity.this, R.anim.rotate);
                    if (rotate != null) {
                        mCircleView.startAnimation(rotate);
                    }
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            mProgress++;
                            mProgressBar.setProgress(mProgress);
                            if (mProgress >= 100) {
                                ToastUtils.showToast(FaceDetectingActivity.this, "网络延时");
                            } else {
                                //每隔1s循环执行run方法
                                mCircleView.postDelayed(this, 1000);
                            }
                        }
                    };
                    mCircleView.postDelayed(r, 1000);

                }else {
                    if(list!=null&&!list.equals("")){
                        ToastUtils.showToast(FaceDetectingActivity.this,list);
                    }else {
                        ToastUtils.showToast(FaceDetectingActivity.this,"尚未获取检测权限");
                    }

                    finish();
                }

            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(FaceDetectingActivity.this,"检测权限获取失败");
                finish();

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }

    @Override
    protected void setupView() {
        super.setupView();
        setTitleText("检测中");
        getJc();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
        detachView();
    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(List<HealthReport> reports) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Utils.deleteTmpFile(new File(Constant.SD_TEMP_IMAGE));
            }
        }).start();
        HealthReport report = reports.get(0);
        HealthReportDetailActivity.start(this, report.getId());
        finish();
    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }
}
